# backend/app.py

from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from models import db, Category, Website
import requests
from bs4 import BeautifulSoup


app = Flask(__name__)
CORS(app)

# 配置数据库 URI（SQLite 示例）
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///navigation.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 初始化数据库
db.init_app(app)


def create_tables():
    with app.app_context():
        db.create_all()
        print("✅ 数据库表已创建")


def fetch_website_info(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
    }
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.encoding = response.apparent_encoding if response.apparent_encoding else 'utf-8'
        soup = BeautifulSoup(response.text, 'html.parser')

        title = soup.title.string.strip() if soup.title else url
        meta_desc = soup.find('meta', attrs={'name': 'description'})
        description = meta_desc['content'].strip() if meta_desc and 'content' in meta_desc.attrs else ''
        return {'title': title, 'description': description}
    except Exception as e:
        print(f"Error fetching {url}: {e}")
        return {'title': url, 'description': ''}


@app.route('/api/categories', methods=['GET'])
def get_categories():
    categories = Category.query.all()
    return jsonify([c.to_dict() for c in categories])


@app.route('/api/categories', methods=['POST'])
def add_category():
    data = request.get_json()
    new_category = Category(name=data['name'])
    db.session.add(new_category)
    db.session.commit()
    return jsonify(new_category.to_dict()), 201


@app.route('/api/categories/<int:id>', methods=['DELETE'])
def delete_category(id):
    category = Category.query.get_or_404(id)
    db.session.delete(category)
    db.session.commit()
    return jsonify({"message": "分类已删除"})


@app.route('/api/websites', methods=['GET'])
def get_websites():
    websites = Website.query.all()
    return jsonify([w.to_dict() for w in websites])


@app.route('/api/websites/category/<int:category_id>', methods=['GET'])
def get_websites_by_category(category_id):
    websites = Website.query.filter_by(category_id=category_id).all()
    return jsonify([w.to_dict() for w in websites])


@app.route('/api/websites', methods=['POST'])
def add_website():
    data = request.get_json()
    new_website = Website(
        name=data['name'],
        url=data['url'],
        category_id=data['category_id']
    )
    db.session.add(new_website)
    db.session.commit()
    return jsonify(new_website.to_dict()), 201


@app.route('/api/websites/<int:id>', methods=['DELETE'])
def delete_website(id):
    website = Website.query.get_or_404(id)
    db.session.delete(website)
    db.session.commit()
    return jsonify({"message": "网址已删除"})


# 👇 新增的抓取接口
@app.route('/api/websites/fetch', methods=['GET'])
def fetch_website_data():
    url = request.args.get('url')
    if not url:
        return jsonify({'error': '缺少URL参数'}), 400

    result = fetch_website_info(url)
    return jsonify(result)


if __name__ == '__main__':
    create_tables()
    app.run(host='0.0.0.0', port=5000, debug=True)